// 渲染模块
import images from './resources.js';

// 初始化渲染器
function initRenderer(canvas) {
    const ctx = canvas.getContext('2d');
    return ctx;
}

// 游戏循环渲染
function render(ctx, engine, canvas, isGameOver) {
    if (isGameOver) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制所有物体
    engine.world.bodies.forEach(body => {
        if (body.label === 'mario' && images.mario.complete) {
            // 绘制马里奥
            ctx.drawImage(
                images.mario,
                body.position.x - 15,
                body.position.y - 20,
                30,
                40
            );
        } else if (body.label === 'enemy' && images.enemy.complete) {
            // 绘制敌人
            ctx.drawImage(
                images.enemy,
                body.position.x - 15,
                body.position.y - 15,
                30,
                30
            );
        } else if (body.label === 'coin' && images.coin.complete) {
            // 绘制金币
            ctx.drawImage(
                images.coin,
                body.position.x - 10,
                body.position.y - 10,
                20,
                20
            );
        } else if (body.label === 'platform' && images.platform.complete) {
            // 绘制平台
            const width = body.bounds.max.x - body.bounds.min.x;
            const height = body.bounds.max.y - body.bounds.min.y;
            
            // 创建平铺模式
            const pattern = ctx.createPattern(images.platform, 'repeat');
            ctx.fillStyle = pattern;
            ctx.fillRect(
                body.position.x - width / 2,
                body.position.y - height / 2,
                width,
                height
            );
        } else if (body.label === 'brick' && images.brick.complete) {
            // 绘制砖块
            ctx.drawImage(
                images.brick,
                body.position.x - 25,
                body.position.y - 25,
                50,
                50
            );
        } else {
            // 如果图片未加载完成，使用默认色块
            ctx.fillStyle = '#aaa';
            const width = body.bounds.max.x - body.bounds.min.x;
            const height = body.bounds.max.y - body.bounds.min.y;
            ctx.fillRect(
                body.position.x - width / 2,
                body.position.y - height / 2,
                width,
                height
            );
        }
    });
}

export { initRenderer, render };